package com.imooc.o2o.service.impl;


import com.imooc.o2o.dao.ShopDao;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.exceptions.ShopOperationException;
import com.imooc.o2o.service.ShopService;
import com.imooc.o2o.util.ImageUtil;
import com.imooc.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.util.Date;
@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopDao shopDao;
    /**
     *  增加店铺
     * @param shop
     * @param shopImg
     * @return
     */
    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, MultipartFile shopImg) {
        //null 判断
        if(shop == null) {
            //店铺信息为空
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }
        try {
            //1.赋初始值
            shop.setEnableStatus(0); //未上架，审核中
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            //1.往数据库增加店铺信息
            int effectedNum = shopDao.insertShop(shop);

            if(effectedNum <= 0) {
                //添加失败
                throw new ShopOperationException("店铺创建失败"); //只有runtimeException时候事务才会回滚
            } else {
                if(shopImg != null) {
                    //存储图片
                    try{
                    addShopImg(shop,shopImg);

                    } catch (Exception e) {
                        throw new ShopOperationException("店铺创建失败" + e.getMessage());
                    }
                    //更新店铺的图片地址
                    effectedNum = shopDao.updateShop(shop);
                    if(effectedNum <= 0) throw new ShopOperationException("更新图片地址失败");
                }

            }

        }catch (Exception e) {
            throw new ShopOperationException("addshop error" + e.getMessage());
        }

        return null;
    }

    private void addShopImg(Shop shop, MultipartFile shopImg) {
        //获取shop图片目录的相对值路径
        String dest = PathUtil.getShopImagePath(shop.getShopId());
        String shopImgAddr = ImageUtil.generateThumbnail(shopImg,dest);
        shop.setShopImg(shopImgAddr);
    }
}
